//
//  KY_MoreViewController.m
//  ShaQueVideo
//
//  Created by huliang on 13-5-9.
//  Copyright (c) 2013年 科悦信达. All rights reserved.
//

#import "KY_MoreViewController.h"
#import "AboutViewController.h"
#import "TuijianAppViewController.h"
@interface KY_MoreViewController ()

@end

@implementation KY_MoreViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.title = @"更多";
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    if ([sinaweibo isLoggedIn])
    {
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"sinaUserName"]) {

            return;
        }
        // https://api.weibo.com/2/users/show.json
        NSString *str = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@",sinaweibo.userID,sinaweibo.accessToken];

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:str]];
        [request startSynchronous];
        NSError *error = [request error];
        if (!error) {

            NSDictionary *dic = [[request responseString] objectFromJSONString];
            NSString *nameString = [dic objectForKey:@"screen_name"];
            NSDictionary *sinaDic = [NSDictionary dictionaryWithObject:nameString forKey:@"screen_name"];
            [[NSUserDefaults standardUserDefaults] setObject:sinaDic forKey:@"sinaUserName"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }

}
- (void)viewDidLoad
{
    [super viewDidLoad];
   
     self.menuSection1TitleArr = [NSArray arrayWithObject:@"绑定新浪微博"];
     self.menuSection2TitleArr = [NSArray arrayWithObjects:@"去AppStore评价一下吧",@"更多精彩应用推荐",@"关于",@"每日更新提醒",nil];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

 if (indexPath.section == 1)
    {
        switch (indexPath.row) {
                
            case 0:
            {

                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=658769424"]];
            }

                break;
             case 1:
            {
                 TuijianAppViewController *viewController = [[TuijianAppViewController alloc] initWithNibName:@"TuijianAppViewController" bundle:nil];
                [self.navigationController pushViewController:viewController animated:YES];
                [viewController release];
            }
                break;
            case 2:
            {
                AboutViewController *viewController = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];
                [self.navigationController pushViewController:viewController animated:YES];
                [viewController release];
                
            }
                break;

            default:
                break;
        }
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {

        case 0:
            return [self.menuSection1TitleArr count];
            break;
        case 1:
            return [self.menuSection2TitleArr count];
            break;
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {


        // WeiboHaoyouCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseStr];

        BangdingCell * cell = [[[NSBundle mainBundle] loadNibNamed:@"BangdingCell" owner:self options:nil] objectAtIndex:0];
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {


            SinaWeibo *sinaweibo = [self sinaweibo];
            if (![sinaweibo isAuthValid])
            {
        
                [cell.bandingBtn  setTitle:@"未绑定" forState:UIControlStateNormal];
                cell.nameLabel.text = @"新浪微博";
                cell.bandingBtn.tag = 0;


            }
            else
            {
                NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"sinaUserName"];
                NSString *nameString = [dic objectForKey:@"screen_name"];
                [cell.bandingBtn  setTitle:@"已绑定" forState:UIControlStateNormal];
                cell.nameLabel.text = [NSString stringWithFormat:@"新浪微博(%@)",nameString];
                cell.bandingBtn.tag = 1;
            }


            cell.typeString = @"sina";
        }
        cell.delegate = self;

        return cell;
    }
        else
        {
            static NSString *cellString = @"cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
            if (cell==nil) {

                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
                

            }
    
            cell.textLabel.text = [self.menuSection2TitleArr objectAtIndex:indexPath.row];

        if (3 == indexPath.row) {

            UISwitch *m_switch = [[UISwitch alloc] initWithFrame:CGRectMake(200, 8, 79, 27)];
            [m_switch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:m_switch];
             NSString *pushString = [[NSUserDefaults standardUserDefaults] objectForKey:@"localpush"];
            
            if ([pushString isEqualToString:@"1"]) {
                
                m_switch.on = YES;
            }
            else
            {
                m_switch.on = NO;
            }
        }

            return cell;
        }

    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(void)switchAction:(id)sender
{
    UISwitch *m_switch = (UISwitch *)sender;
    if (m_switch.on == YES) {

        UIApplication *app = [UIApplication sharedApplication];
        NSArray *localArray = [app scheduledLocalNotifications];
        //声明本地通知对象
         
        if (localArray) {
            for (UILocalNotification *noti in localArray) {
                NSDictionary *dict = noti.userInfo;
                if (dict) {
                    NSString *inKey = [dict objectForKey:@"key"];
                    if ([inKey isEqualToString:@"name"]) {

                        return;
                        
                    }
                }
            }
        }
        

       [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"localpush"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];//分配内存，用以存放日期格式
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//定义格式
        NSString * locationString = [formatter stringFromDate:[NSDate date]];
        NSArray *m_array = [locationString componentsSeparatedByString:@" "];
        NSString *fiveString = [NSString stringWithFormat:@"%@ 17:00:00",[m_array objectAtIndex:0]];

        NSDateFormatter * m_formatter = [[NSDateFormatter alloc]init];
        [m_formatter setDateStyle:NSDateFormatterMediumStyle];
        [m_formatter setTimeStyle:NSDateFormatterShortStyle];
        [m_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate * date = [m_formatter dateFromString:fiveString];//把字符串转换成Date格式

        
        UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];

        if (notification != nil) {
            // 设置推送时间
            notification.fireDate = date;
            // 设置时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            // 设置重复间隔
            notification.repeatInterval = kCFCalendarUnitDay;
            // 推送声音
            notification.soundName = UILocalNotificationDefaultSoundName;
            // 推送内容
            notification.alertBody = @"傻缺视频有更新,搞笑瞬间不容错过!";
            //显示在icon上的红色圈中的数子
            notification.applicationIconBadgeNumber += 1;
            //设置userinfo 方便在之后需要撤销的时候使用
            NSDictionary *info = [NSDictionary dictionaryWithObject:@"name"forKey:@"key"];
            notification.userInfo = info;
            //添加推送到UIApplication
            UIApplication *app = [UIApplication sharedApplication];
            [app scheduleLocalNotification:notification];

        }


}
    else
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"localpush"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        UIApplication *app = [UIApplication sharedApplication];
        //获取本地推送数组
        NSArray *localArray = [app scheduledLocalNotifications];
        //声明本地通知对象
        UILocalNotification *localNotification = nil;
        if (localArray) {
            for (UILocalNotification *noti in localArray) {
                NSDictionary *dict = noti.userInfo;
                if (dict) {
                    NSString *inKey = [dict objectForKey:@"key"];
                    if ([inKey isEqualToString:@"name"]) {
                        if (localNotification){
                            [localNotification release];
                            localNotification = nil;
                        }
                        localNotification = [noti retain];
                        break;
                    }
                }
            }
        
            //判断是否找到已经存在的相同key的推送
            if (!localNotification) {
                //不存在初始化
                localNotification = [[UILocalNotification alloc] init];
            }
            
            if (localNotification) {
                //不推送 取消推送
                [app cancelLocalNotification:localNotification];
                [localNotification release];
                return;
            }
        }

    }
}
- (SinaWeibo *)sinaweibo
{
    KY_AppDelegate  *delegate = (KY_AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.sinaweibo.delegate = self;
    return delegate.sinaweibo;
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];

    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    [self storeAuthData];
    NSString *str = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@",sinaweibo.userID,sinaweibo.accessToken];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:str]];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {

        NSDictionary *dic = [[request responseString] objectFromJSONString];
        NSString *nameString = [dic objectForKey:@"screen_name"];
        NSDictionary *sinaDic = [NSDictionary dictionaryWithObject:nameString forKey:@"screen_name"];
        [[NSUserDefaults standardUserDefaults] setObject:sinaDic forKey:@"sinaUserName"];
        [[NSUserDefaults standardUserDefaults] synchronize];

    }
    [self.menuTableView reloadData];
}

-(void)btnActionOnSina
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo logIn];
}
-(void)btnActionOnSinaJieBang
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo logOut];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"sinaUserName"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.menuTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
